package com.kili.file.config.elect;

import com.kili.file.config.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * @author fenny
 * @since 2019/07/24
 */
@Slf4j
public class DynamicElectResolver implements HandlerMethodArgumentResolver {

    @Resource
    private DynamicElectConfiguration dynamicElectConfiguration;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(DynamicElect.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
        Object result;

        //Getting annotation information
        DynamicElect dynamicElect = methodParameter.getParameterAnnotation(DynamicElect.class);
        String beanName = null;
        switch (dynamicElect.mode()) {
            case PARAMETER:
                beanName = nativeWebRequest.getParameter(dynamicElect.key());
                break;
            default:
                break;
        }
        log.info("key in parameter = {}", beanName);

        //Get the corresponding dynamic election group,Get the corresponding beanName from the mapping configuration
        LinkedHashMap<String, String> values = dynamicElectConfiguration.getMapper().get(dynamicElect.group());
        //Failure to find the corresponding mapping makes the first default

        if (!StringUtils.hasText(beanName = values.get(beanName))) {
            beanName = values.get(values.keySet().iterator().next());
        }

        log.info("Setting the implementation class name dynamically = {}", beanName);
        //Find the corresponding implementation class in the container and return it
        result = SpringContextHolder.getBean(beanName);

        return result;
    }



}
